const express = require('express')
const router = express.Router()
const multipart = require('../../middleware/content-type/multypart')
const { insertBannerList, readBannerList, removeBannerList, removeBannerListAll } = require('../../model/mongo')

router.use(multipart('./server/img/swiper'))

router.post('/add', async (req, res) => {
    let { img, link, alt, fileList } = req.body
    const result = {
        code: 200,
        method: req.method,
        msg: '添加成功',
        data: '返回数据'
    }
    result.data = await insertBannerList({
        // 兼容传字符串和form-data文件
        img: (fileList && fileList[0].path) || img,
        alt: alt,
        link: link,
    })
    res.send(JSON.stringify(result))
})

router.get('/list', async (req, res) => {
    const result = {
        code: 200,
        method: req.method,
        msg: '获取轮播图数据成功',
        data: []
    }
    result.data = await readBannerList()
    res.send(JSON.stringify(result))
})

router.get('/delete', async (req, res) => {
    const { bannerid } = req.query
    const result = {
        code: 200,
        msg: '状态信息'
    }
    try {
        result.msg = await removeBannerList(bannerid)
    } catch (err) {
        result.code = 404
        result.msg = err
    }
    res.send(JSON.stringify(result))
})

router.get('/removeAll', async (req, res) => {
    const result = {
        code: 200,
        msg: '状态信息'
    }
    try {
        result.msg = await removeBannerListAll()
    } catch (err) {
        result.code = 400
        result.msg = err
    }
    res.send(JSON.stringify(result))
})

module.exports = router
